package com.edgclub.edg.utils.util;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;

import com.xuanwu.ImageUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

/**
 * 图片工具
 * 
 * @author eric
 * 
 */
public class BitmapUtility {

	public static final int ALL = 0x00;
	public static final int TOP = 0x01;
	public static final int LEFT = 0x02;
	public static final int RIGHT = 0x03;
	public static final int BOTTOM = 0x04;

	/** 水平方向模糊度 */
	private static float hRadius = 1;
	/** 竖直方向模糊度 */
	private static float vRadius = 1;
	/** 模糊迭代度 */
	private static int iterations = 1;

	/**
	 * 
	 * 指定图片的切边，对图片进行圆角处理
	 * 
	 * @param bitmap
	 *            需要被切圆角的图片
	 * @param roundPx
	 *            要切的像素大小
	 * @return 处理后的图片对象
	 * 
	 */
	public static Bitmap fillet(int type, Bitmap bitmap, int roundPx) {
		try {
			// 其原理就是：先建立一个与图片大小相同的透明的Bitmap画板
			// 然后在画板上画出一个想要的形状的区域。
			// 最后把源图片帖上。
			final int width = bitmap.getWidth();
			final int height = bitmap.getHeight();

			Bitmap paintingBoard = Bitmap.createBitmap(width, height,
					Config.ARGB_8888);
			Canvas canvas = new Canvas(paintingBoard);
			canvas.drawARGB(Color.TRANSPARENT, Color.TRANSPARENT,
					Color.TRANSPARENT, Color.TRANSPARENT);

			final Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setColor(Color.BLACK);

			if (TOP == type) {
				clipTop(canvas, paint, roundPx, width, height);
			} else if (LEFT == type) {
				clipLeft(canvas, paint, roundPx, width, height);
			} else if (RIGHT == type) {
				clipRight(canvas, paint, roundPx, width, height);
			} else if (BOTTOM == type) {
				clipBottom(canvas, paint, roundPx, width, height);
			} else {
				clipAll(canvas, paint, roundPx, width, height);
			}

			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			// 贴子图
			final Rect src = new Rect(0, 0, width, height);
			canvas.drawBitmap(bitmap, src, src, paint);
			return paintingBoard;
		} catch (Exception exp) {
			return bitmap;
		}
	}

	public interface Option {
		int NONE = 0x0;
		int SCALE_UP = 0x1;
		int RECYCLE_INPUT = 0x2;
	}

	/**
	 * 指定长度宽度进行缩放
	 * 
	 * @param source
	 *            源图片
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 * @return 处理后的图片
	 */
	public static Bitmap extract(Bitmap source, int targetWidth,
			int targetHeight) {
		return extractThumbnail(source, targetWidth, targetHeight, Option.NONE);
	}

	/**
	 * 按指定比例缩放
	 * 
	 * @param source
	 *            源图片
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 * @return 处理后的图片
	 */
	public static Bitmap prorate(Bitmap source, int targetWidth,
			int targetHeight) {
		if (source == null)
			return null;

		int srcWidth = source.getWidth();
		int srcHeight = source.getHeight();
		if (srcWidth < srcHeight) {
			targetHeight = srcHeight * targetWidth / srcWidth;
		} else {
			targetWidth = srcWidth * targetHeight / srcHeight;
		}
		return extractThumbnail(source, targetWidth, targetHeight, Option.NONE);
	}

	/**
	 * 对图片进行缩放
	 * 
	 * @param source
	 * @param targetWidth
	 * @param targetHeight
	 * @param options
	 * @return
	 */

	public static Bitmap extractThumbnail(Bitmap source, int targetWidth,
			int targetHeight, int options) {
		if (source == null) {
			return null;
		}
		float scale;
		if (source.getWidth() < source.getHeight()) {
			scale = targetWidth / (float) source.getWidth();
		} else {
			scale = targetHeight / (float) source.getHeight();
		}
		Matrix matrix = new Matrix();
		matrix.setScale(scale, scale);
		return transform(matrix, source, targetWidth, targetHeight,
				Option.SCALE_UP | options);
	}

	/**
	 * 缩放的业务
	 * 
	 * @param scaler
	 * @param source
	 * @param targetWidth
	 * @param targetHeight
	 * @param options
	 * @return
	 */
	private static Bitmap transform(Matrix scaler, Bitmap source,
			int targetWidth, int targetHeight, int options) {
		boolean scaleUp = (options & Option.SCALE_UP) != 0;
		boolean recycle = (options & Option.RECYCLE_INPUT) != 0;

		int deltaX = source.getWidth() - targetWidth;
		int deltaY = source.getHeight() - targetHeight;
		if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
			Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight,
					Config.ARGB_8888);
			Canvas c = new Canvas(b2);
			int deltaXHalf = Math.max(0, deltaX / 2);
			int deltaYHalf = Math.max(0, deltaY / 2);
			Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf
					+ Math.min(targetWidth, source.getWidth()), deltaYHalf
					+ Math.min(targetHeight, source.getHeight()));
			int dstX = (targetWidth - src.width()) / 2;
			int dstY = (targetHeight - src.height()) / 2;
			Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight
					- dstY);
			c.drawBitmap(source, src, dst, null);
			if (recycle) {
				source.recycle();
			}
			return b2;
		}
		float bitmapWidthF = source.getWidth();
		float bitmapHeightF = source.getHeight();

		float bitmapAspect = bitmapWidthF / bitmapHeightF;
		float viewAspect = (float) targetWidth / targetHeight;

		if (bitmapAspect > viewAspect) {
			float scale = targetHeight / bitmapHeightF;
			if (scale < .9F || scale > 1F) {
				scaler.setScale(scale, scale);
			} else {
				scaler = null;
			}
		} else {
			float scale = targetWidth / bitmapWidthF;
			if (scale < .9F || scale > 1F) {
				scaler.setScale(scale, scale);
			} else {
				scaler = null;
			}
		}

		Bitmap b1;
		if (scaler != null) {
			b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(),
					source.getHeight(), scaler, true);
		} else {
			b1 = source;
		}
		if (recycle && b1 != source) {
			source.recycle();
		}
		int dx1 = Math.max(0, b1.getWidth() - targetWidth);
		int dy1 = Math.max(0, b1.getHeight() - targetHeight);
		Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth,
				targetHeight);
		if (b2 != b1) {
			if (recycle || b1 != source) {
				b1.recycle();
			}
		}
		return b2;
	}

	/**
	 * 左边切片
	 *
	 * @param canvas
	 * @param paint
	 * @param offset
	 * @param width
	 * @param height
	 */
	private static void clipLeft(final Canvas canvas, final Paint paint,
			int offset, int width, int height) {
		final Rect block = new Rect(offset, 0, width, height);
		canvas.drawRect(block, paint);
		final RectF rectF = new RectF(0, 0, offset * 2, height);
		canvas.drawRoundRect(rectF, offset, offset, paint);
	}

	/**
	 * 右边切片
	 *
	 * @param canvas
	 * @param paint
	 * @param offset
	 * @param width
	 * @param height
	 */
	private static void clipRight(final Canvas canvas, final Paint paint,
			int offset, int width, int height) {
		final Rect block = new Rect(0, 0, width - offset, height);
		canvas.drawRect(block, paint);
		final RectF rectF = new RectF(width - offset * 2, 0, width, height);
		canvas.drawRoundRect(rectF, offset, offset, paint);
	}

	/**
	 * 上方切片
	 *
	 * @param canvas
	 * @param paint
	 * @param offset
	 * @param width
	 * @param height
	 */
	private static void clipTop(final Canvas canvas, final Paint paint,
			int offset, int width, int height) {
		final Rect block = new Rect(0, offset, width, height);
		canvas.drawRect(block, paint);
		final RectF rectF = new RectF(0, 0, width, offset * 2);
		canvas.drawRoundRect(rectF, offset, offset, paint);
	}

	/**
	 * 下方切片
	 *
	 * @param canvas
	 * @param paint
	 * @param offset
	 * @param width
	 * @param height
	 */
	private static void clipBottom(final Canvas canvas, final Paint paint,
			int offset, int width, int height) {
		final Rect block = new Rect(0, 0, width, height - offset);
		canvas.drawRect(block, paint);
		final RectF rectF = new RectF(0, height - offset * 2, width, height);
		canvas.drawRoundRect(rectF, offset, offset, paint);
	}

	/**
	 * 全部切片
	 *
	 * @param canvas
	 * @param paint
	 * @param offset
	 * @param width
	 * @param height
	 */
	private static void clipAll(final Canvas canvas, final Paint paint,
			int offset, int width, int height) {
		final RectF rectF = new RectF(0, 0, width, height);
		canvas.drawRoundRect(rectF, offset, offset, paint);
	}

	/**
	 * 获得圆角
	 *
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = bitmap.getWidth() / 2;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(
				Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 高斯模糊
	 */
	public static Bitmap BoxBlurFilter(Bitmap bmp) {
		int width = bmp.getWidth();
		int height = bmp.getHeight();
		int[] inPixels = new int[width * height];
		int[] outPixels = new int[width * height];
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Config.ARGB_8888);
		bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
		for (int i = 0; i < iterations; i++) {
			blur(inPixels, outPixels, width, height, hRadius);
			blur(outPixels, inPixels, height, width, vRadius);
		}
		blurFractional(inPixels, outPixels, width, height, hRadius);
		blurFractional(outPixels, inPixels, height, width, vRadius);
		bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

	public static void blur(int[] in, int[] out, int width, int height,
			float radius) {
		int widthMinus1 = width - 1;
		int r = (int) radius;
		int tableSize = 2 * r + 1;
		int divide[] = new int[256 * tableSize];

		for (int i = 0; i < 256 * tableSize; i++)
			divide[i] = i / tableSize;

		int inIndex = 0;

		for (int y = 0; y < height; y++) {
			int outIndex = y;
			int ta = 0, tr = 0, tg = 0, tb = 0;

			for (int i = -r; i <= r; i++) {
				int rgb = in[inIndex + clamp(i, 0, width - 1)];
				ta += (rgb >> 24) & 0xff;
				tr += (rgb >> 16) & 0xff;
				tg += (rgb >> 8) & 0xff;
				tb += rgb & 0xff;
			}

			for (int x = 0; x < width; x++) {
				out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
						| (divide[tg] << 8) | divide[tb];

				int i1 = x + r + 1;
				if (i1 > widthMinus1)
					i1 = widthMinus1;
				int i2 = x - r;
				if (i2 < 0)
					i2 = 0;
				int rgb1 = in[inIndex + i1];
				int rgb2 = in[inIndex + i2];

				ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
				tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
				tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
				tb += (rgb1 & 0xff) - (rgb2 & 0xff);
				outIndex += height;
			}
			inIndex += width;
		}
	}

	public static void blurFractional(int[] in, int[] out, int width,
			int height, float radius) {
		radius -= (int) radius;
		float f = 1.0f / (1 + 2 * radius);
		int inIndex = 0;

		for (int y = 0; y < height; y++) {
			int outIndex = y;

			out[outIndex] = in[0];
			outIndex += height;
			for (int x = 1; x < width - 1; x++) {
				int i = inIndex + x;
				int rgb1 = in[i - 1];
				int rgb2 = in[i];
				int rgb3 = in[i + 1];

				int a1 = (rgb1 >> 24) & 0xff;
				int r1 = (rgb1 >> 16) & 0xff;
				int g1 = (rgb1 >> 8) & 0xff;
				int b1 = rgb1 & 0xff;
				int a2 = (rgb2 >> 24) & 0xff;
				int r2 = (rgb2 >> 16) & 0xff;
				int g2 = (rgb2 >> 8) & 0xff;
				int b2 = rgb2 & 0xff;
				int a3 = (rgb3 >> 24) & 0xff;
				int r3 = (rgb3 >> 16) & 0xff;
				int g3 = (rgb3 >> 8) & 0xff;
				int b3 = rgb3 & 0xff;
				a1 = a2 + (int) ((a1 + a3) * radius);
				r1 = r2 + (int) ((r1 + r3) * radius);
				g1 = g2 + (int) ((g1 + g3) * radius);
				b1 = b2 + (int) ((b1 + b3) * radius);
				a1 *= f;
				r1 *= f;
				g1 *= f;
				b1 *= f;
				out[outIndex] = (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;
				outIndex += height;
			}
			out[outIndex] = in[width - 1];
			inIndex += width;
		}
	}

	public static int clamp(int x, int a, int b) {
		return (x < a) ? a : (x > b) ? b : x;
	}

	/**
	 * 是否是一个完整的url
	 *
	 * @param url
	 * @return
	 */
	public static boolean isImg(String url) {
		String pattern = "^((http://)|(https://)|(ftp://)).*?.(png|jpg|jpeg|gif|bmp)";

		return Pattern.matches(pattern, url);
	}

	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	/**
	 * 获取图片对象
	 *
	 * @param bytes
	 * @param opts
	 * @return
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 * 读取图片
	 *
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		buffer = null;
		return data;

	}

	/**
	 * 图片压缩方法实现
	 *
	 * @param srcPath
	 *            原图地址
	 * @param finishPath
	 *            压缩后保存图片地址
	 *            保存的文件夹路径
	 * @return
	 */
	public static int compressImage(String srcPath, String finishPath) {

		File destinationFile = new File(finishPath);
		if (!destinationFile.exists()) {
			File dir = destinationFile.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
		}

		File file = new File(srcPath);
		long length = file.length();
		int level = 80;
		int compress_level = 1;

		if (length > 1024 * 150) {
			level = 80;
			compress_level = 1;

			if (length >= 1024 * 150  && length < 1024 * 1024*2) {
//				level = 60;
//				compress_level = 1;
				compressPNGFromBitmap(srcPath, finishPath,300);
				return 1;
			}
			if (length >= 1024 * 1024 * 2 && length < 1024 * 1024 * 4) {
				// 3mb
				level = 40;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 4 && length <= 1024 * 1024 * 5) {
				// 4mb
				level = 40;
				compress_level = 1;
			}
			// 5mb
			if (length >= 1024 * 1024 * 5) {
				level = 40;
				compress_level = 1;
			}

		}  else  {
//			level = 90;
//			compress_level = 0;
			try {
				FileUtility.copy(srcPath, finishPath);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 1;
		}
//		else {
//			level = 95;
//			compress_level = 0;

//		}

		return new ImageUtil().compressJPGFromFile(srcPath, finishPath, 0,
				compress_level, level);
	}

	public static int compressImage80(String srcPath, String finishPath) {

		File destinationFile = new File(finishPath);
		if (!destinationFile.exists()) {
			File dir = destinationFile.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
		}

		File file = new File(srcPath);
		long length = file.length();
		int level = 80;
		int compress_level = 1;

		if (length > 1024 * 150) {
			level = 80;
			compress_level = 1;
		}  else  {
			try {
				FileUtility.copy(srcPath, finishPath);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 1;
		}
		return new ImageUtil().compressJPGFromFile(srcPath, finishPath, 0,
				compress_level, level);
	}

	/**
	 * 质量压缩
	 *
	 * @param image
	 * @return
	 */
	public static int compressImage(Bitmap image, String finishPath) {

		File destinationFile = new File(finishPath);
		if (!destinationFile.exists()) {
			File dir = destinationFile.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
		}

		saveImage(image, finishPath);

		File file = new File(finishPath);
		long length = file.length();
		int level = 80;
		int compress_level = 1;

		if (length > 1024 * 150) {
			level = 80;
			compress_level = 1;

			if (length >= 1024 * 500  && length < 1024 * 1024) {
				level = 70;
				compress_level = 1;
			}
			// 1mb
			if (length >= 1024 * 1024  && length < 1024 * 1024 * 2) {
				level = 60;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 2 && length < 1024 * 1024 * 3) {
				// 2mb
				level = 40;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 3 && length < 1024 * 1024 * 4) {
				// 3mb
				level = 30;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 4 && length <= 1024 * 1024 * 5) {
				// 4mb
				level = 30;
				compress_level = 1;
			}
			// 5mb
			if (length >= 1024 * 1024 * 5) {
				level = 30;
				compress_level = 1;
			}

		} else if (length > 1024 * 80 && length <= 1024 * 150) {
			level = 80;
			compress_level = 0;
		} else if (length > 1024 * 50 && length <= 1024 * 80) {
			level = 90;
			compress_level = 0;
		} else {
			level = 95;
			compress_level = 0;
		}

		return new ImageUtil().compressJPGFromFile(finishPath, finishPath, 0,
				compress_level, level);
	}

	/**
	 * 质量压缩
	 *
	 * @param image
	 * @return
	 */
	public static int compressSimpleImage(Bitmap image, String finishPath) {

		File destinationFile = new File(finishPath);
		if (!destinationFile.exists()) {
			File dir = destinationFile.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
		}
		saveImage(image, finishPath);

		File file = new File(finishPath);
		long length = file.length();
		int level = 40;
		int compress_level = 1;

		if (length > 1024 * 150) {
			level = 30;
			compress_level = 1;
			// 1mb
			if (length > 1024 * 1024  && length < 1024 * 1024 * 2) {
				level = 20;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 2 && length < 1024 * 1024 * 3) {
				// 2mb
				level = 20;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 3 && length < 1024 * 1024 * 4) {
				// 3mb
				level = 20;
				compress_level = 1;
			}
			if (length >= 1024 * 1024 * 4 && length <= 1024 * 1024 * 5) {
				// 4mb
				level = 20;
				compress_level = 1;
			}
			// 5mb
			if (length >= 1024 * 1024 * 5) {
				level = 20;
				compress_level = 1;
			}

		} else if (length > 1024 * 80 && length <= 1024 * 150) {
			level = 30;
			compress_level = 0;
		} else if (length > 1024 * 30 && length <= 1024 * 80) {
			level = 30;
			compress_level = 0;
		} else {
			level = 95;
			compress_level = 0;
		}

		return new ImageUtil().compressJPGFromFile(finishPath, finishPath, 0,
				compress_level, level);
	}

	/**
	 * 质量压缩
	 *
	 * @return
	 */
	public static int compressImage(String finishPath) {

		File file = new File(finishPath);
		long length = file.length();
		int level = 80;
		int compress_level = 1;

		if (length > 1024 * 150) {
			level = 70;
			compress_level = 0;
			// 1mb
			if (length > 1024 * 150 * 10 && length < 1024 * 150 * 20) {
				level = 50;
				compress_level = 1;
			}
			if (length >= 1024 * 150 * 20 && length < 1024 * 150 * 30) {
				// 2mb
				level = 45;
				compress_level = 1;
			}
			if (length >= 1024 * 150 * 30 && length < 1024 * 150 * 40) {
				// 3mb
				level = 40;
				compress_level = 1;
			}
			if (length >= 1024 * 150 * 40 && length < 1024 * 150 * 50) {
				// 4mb
				level = 35;
				compress_level = 1;
			}
			// 5mb
			if (length >= 1024 * 150 * 50) {
				level = 30;
				compress_level = 1;
			}

		} else {
			level = 90;
			compress_level = 0;
		}
		File destinationFile = new File(finishPath);
		if (!destinationFile.exists()) {
			File dir = destinationFile.getParentFile();
			if (dir != null && !dir.exists()) {
				dir.mkdirs();
			}
		}
		return new ImageUtil().compressJPGFromFile(finishPath, finishPath, 0,
				compress_level, level);
	}

	/**
	 * 质量压缩
	 *
	 * @return
	 */
	public static int compressJPGFromBitmap(Bitmap bitmap,
			String outputfilename, int orientation, int compress_level) {

		return new ImageUtil().compressJPGFromBitmap(bitmap, outputfilename,
				orientation, compress_level);
	}

	/**
	 * 保存图片
	 *
	 * @param image
	 * @return
	 */
	public static boolean saveImage(Bitmap image, String finishPath) {

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(FileUtility.createFile(finishPath));
			image.compress(CompressFormat.JPEG, 100, out);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
	 public static void saveFile(Bitmap bm, String path) throws IOException {
	        File dirFile = new File(path);
	        if(!dirFile.exists()){
	        	FileUtility.createFile(path);
	        }
	        File myCaptureFile = new File(path);
	        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
	        bm.compress(CompressFormat.JPEG, 80, bos);
	        bos.flush();
	        bos.close();
	    }
	/**
	 * 防止内存溢出的图片读取
	 *
	 * @param context
	 * @return
	 */
	public static Drawable decodeFile(Context context, InputStream inputStream) {

		Options o = new Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(inputStream, null, o);

		final int REQUIRED_SIZE = 400;

		int scale = 1;
		while (o.outWidth / scale / 2 >= REQUIRED_SIZE
				&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
			scale *= 2;

		Options o2 = new Options();
		o2.inSampleSize = scale;
		o2.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, o2);
		ImageView iv = new ImageView(context);
		iv.setImageBitmap(bitmap);
		return iv.getDrawable();

	}

//	public static Bitmap scaleUserInfoImage(Context context, Bitmap bitmap) {
//		int bWidth = bitmap.getWidth();
//		int height = bitmap.getHeight();
//
//		int screenW = DensityUtils.getScreenW((Activity) context);
//
//		/* 设置图片放大的比例 */
//		double scale = screenW / bWidth;
//		/* 产生reSize后的Bitmap对象 */
//		Matrix matrix = new Matrix();
//		matrix.postScale((float) scale, (float) scale);
//
//		Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bWidth, height,
//				matrix, false);
//		Bitmap output = Bitmap.createBitmap(resizeBitmap.getWidth(),
//				resizeBitmap.getHeight(), Config.ARGB_8888);
//		Canvas canvas = new Canvas(output);
//		Paint paint = new Paint();
//		// 画图片需要的尺寸
//		Rect rect = new Rect(0, 0, resizeBitmap.getWidth(), (int) context
//				.getResources().getDimension(R.dimen.userinfobg));
//		paint.setAntiAlias(true);
//		paint.setFilterBitmap(true);
//		paint.setDither(true);
//		canvas.drawARGB(0, 0, 0, 0);
//		canvas.drawRect(rect, paint);
//		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//		// 将输出的图片画在最下层
//		canvas.drawBitmap(resizeBitmap, rect, rect, paint);
//
//		bitmap = null;
//		resizeBitmap = null;
//		return output;
//
//	}

	/**
	 * 旋转图片
	 *
	 * @param bitmap
	 *            原始图片
	 * @param degrees
	 *            原始图片的角度
	 * @return Bitmap 旋转后的图片
	 */
	public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
		if (degrees == 0 || null == bitmap) {
			return bitmap;
		}
		Matrix matrix = new Matrix();
		matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
		Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);
		if (null != bitmap && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
		return bmp;
	}

	/**
	 * 以最省内存的方式读取本地资源的图片
	 *
	 * @param context
	 *
	 * @param resId
	 *
	 * @return
	 */
	public static Bitmap readBitmap(Context context, int resId) {
		Options opt = new Options();
		opt.inPreferredConfig = Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/**
	 * 以最省内存的方式读取本地资源的图片
	 *
	 * @param context
	 *
	 * @param resId
	 *
	 * @return
	 */
	public static Bitmap readBitmap2(Context context, int resId) {
		Options opt = new Options();
		opt.inPreferredConfig = Config.ARGB_8888;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/**
	 * 通过uri获取真实的图片路径
	 *
	 * @param activity
	 * @param uri
	 * @return
	 */
	public static String getPathFromImagePath(Activity activity, Uri uri) {
		Cursor cursor = activity
				.managedQuery(uri,
						new String[] { MediaStore.Images.Media.DATA }, null,
						null, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				return cursor.getString(cursor
						.getColumnIndex(MediaStore.Images.Media.DATA));
			}
		} else {
			String path = Uri.decode(uri.toString().substring(
					"file://".length(), uri.toString().length()));
			if (path.endsWith("jpg") || path.endsWith("png")
					|| path.endsWith("jpeg")) {
				return path;
			} else {
				return "typeerror";
			}
		}
		return "";
	}

	/**
	 * 通过uri获取图片
	 *
	 * @param uri
	 * @return
	 */
	public static Bitmap getBitmapFromUri(Context context, Uri uri) {
		try {
			// 读取uri所在的图片

			Options opt = new Options();
			opt.inPreferredConfig = Config.RGB_565;
			opt.inPurgeable = true;
			opt.inInputShareable = true;
			opt.inSampleSize = 4;

			return BitmapFactory.decodeStream(context.getContentResolver()
					.openInputStream(uri), null, opt);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通过uri获取图片
	 *
	 * @param uri
	 * @return
	 */
	public static Bitmap getBitmapFromUri2(Context context, Uri uri) {
		try {
			// 读取uri所在的图片

			Options opt = new Options();
			opt.inPreferredConfig = Config.RGB_565;
			opt.inPurgeable = true;
			opt.inInputShareable = true;
			opt.inSampleSize = 2;

			return BitmapFactory.decodeStream(context.getContentResolver()
					.openInputStream(uri), null, opt);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static  Bitmap loadImageFromUrl(String url) throws Exception  {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        HttpResponse response = client.execute(getRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK)  {
            Log.e("PicShow", "Request URL failed, error code =" + statusCode);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.e("PicShow", "HttpEntity is null");
        }
        InputStream is = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            is = entity.getContent();
            byte[] buf = new byte[1024];
            int readBytes = -1;
            while ((readBytes = is.read(buf)) != -1) {
                baos.write(buf, 0, readBytes);
            }
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (is != null) {
                is.close();
            }
        }
        byte[] imageArray = baos.toByteArray();
        return BitmapFactory.decodeByteArray(
                imageArray, 0, imageArray.length);
}
	/**
	 * 通过uri获取图片
	 *
	 * @param uri
	 * @return
	 */
	public static Bitmap getBitmapFromUri(Context context, Uri uri, String path) {
		try {
			// 读取uri所在的图片

			Bitmap bitmap = loadBitmap(context, uri);

			int digree = 0;
			ExifInterface exif = null;
			try {
				exif = new ExifInterface(path);
			} catch (IOException e) {
				e.printStackTrace();
				exif = null;
			}
			if (exif != null) {
				// 读取图片中相机方向信息
				int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_UNDEFINED);
				// 计算旋转角度
				switch (ori) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					digree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					digree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					digree = 270;
					break;
				default:
					digree = 0;
					break;
				}
			}
			if (digree != 0) {
				// 旋转图片
				Matrix m = new Matrix();
				m.postRotate(digree);
				bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
						bitmap.getHeight(), m, true);
			}
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 图片转成string
	 *
	 * @param bitmap
	 * @return
	 */
	public static String convertIconToString(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
		bitmap.compress(CompressFormat.PNG, 100, baos);
		byte[] appicon = baos.toByteArray();// 转为byte数组
		return Base64.encodeToString(appicon, Base64.DEFAULT);

	}

	public static int getDigree(String imgpath) {
		int digree = 0;
		ExifInterface exif = null;
		try {
			exif = new ExifInterface(imgpath);
		} catch (IOException e) {
			e.printStackTrace();
			exif = null;
		}
		if (exif != null) {
			// 读取图片中相机方向信息
			int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_UNDEFINED);
			// 计算旋转角度
			switch (ori) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				digree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				digree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				digree = 270;
				break;
			default:
				digree = 0;
				break;
			}
		}
		return digree;
	}

	public static Bitmap loadBitmap(Context context, Uri uri) {
		Bitmap pRet = null;
		if (null == context) {
			return pRet;
		}
		if (null == uri) {
			return pRet;
		}

		InputStream is = null;
		int sampleSize = 1;
		Options opt = new Options();

		boolean bool = true;
		while (bool) {
			try {
				is = context.getContentResolver().openInputStream(uri);
				opt.inSampleSize = sampleSize;
				pRet = null;
				pRet = BitmapFactory.decodeStream(is, null, opt);
				bool = false;
			} catch (OutOfMemoryError e) {
				sampleSize *= 2;
				if (sampleSize > (1 << 10)) {
					bool = false;
				}
			} catch (Throwable e) {
				bool = false;
			} finally {
				try {
					is.close();
				} catch (Exception e2) {
				}
			}
		}

		return pRet;
	}


	public static void compressPNGFromBitmap(String imagepath,String savepath,int maxkb){
		try {
			Options newOpts = new Options();
			//开始读入图片，此时把options.inJustDecodeBounds 设回true了
			newOpts.inJustDecodeBounds = true;
			Bitmap bitmap = BitmapFactory.decodeFile(imagepath,newOpts);//此时返回bm为空

			newOpts.inJustDecodeBounds = false;
			int w = newOpts.outWidth;
			int h = newOpts.outHeight;
			//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
			float hh = 1920f;//这里设置高度为800f
			float ww = 1080f;//这里设置宽度为480f
			//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
			int be = 1;//be=1表示不缩放
			if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
				be = (int) (newOpts.outWidth / ww);
			} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
				be = (int) (newOpts.outHeight / hh);
			}
			if (be <= 0)
				be = 1;
			newOpts.inSampleSize = be;//设置缩放比例
			//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
			bitmap = BitmapFactory.decodeFile(imagepath, newOpts);
//		Bitmap bitmap=decodeSampledBitmapFromFile(imagepath,srcWidth,srcHeight);
//		compressBitmap(bitmap,50);
			saveImage(compressBitmap(bitmap,maxkb),savepath);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	/**
	 * 质量压缩
	 * @author ping 2015-register_1-5 下午1:29:58
	 * @param image
	 * @param maxkb
	 * @return
	 */
	public static Bitmap compressBitmap(Bitmap image,int maxkb) {
		//L.showlog(压缩图片);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(CompressFormat.JPEG, 90, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 90;
//		Log.i(test,原始大小 + baos.toByteArray().length);
		while (baos.toByteArray().length / 1024 > maxkb) { // 循环判断如果压缩后图片是否大于(maxkb)50kb,大于继续压缩
//			Log.i(test,压缩一次!);
			baos.reset();// 重置baos即清空baos
			options -= 10;// 每次都减少10
			image.compress(CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			if(options<1)break;
		}
//		Log.i(test,压缩后大小 + baos.toByteArray().length);
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	/**
	 * 官网：获取压缩后的图片
	 *
	 * @param res
	 * @param resId
	 * @param reqWidth
	 *            所需图片压缩尺寸最小宽度
	 * @param reqHeight
	 *            所需图片压缩尺寸最小高度
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromFile(String filepath,
			int reqWidth, int reqHeight) {
		final Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filepath, options);

		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filepath, options);
	}
	/**
	 * 计算压缩比例值(改进版 by touch_ping)
	 *
	 * 原版2>4>8...倍压缩
	 * 当前2>3>4...倍压缩
	 *
	 * @param options
	 *            解析图片的配置信息
	 * @param reqWidth
	 *            所需图片压缩尺寸最小宽度O
	 * @param reqHeight
	 *            所需图片压缩尺寸最小高度
	 * @return
	 */
	public static int calculateInSampleSize(Options options,
			int reqWidth, int reqHeight) {

		final int picheight = options.outHeight;
		final int picwidth = options.outWidth;
		Log.i("test", "原尺寸:" +  picwidth +" *" +picheight);

		int targetheight = picheight;
		int targetwidth = picwidth;
		int inSampleSize = 1;

		if (targetheight > reqHeight || targetwidth > reqWidth) {
			while (targetheight  >= reqHeight
					&& targetwidth>= reqWidth) {
				Log.i("test","压缩:" +inSampleSize + "倍");
				inSampleSize += 1;
				targetheight = picheight/inSampleSize;
				targetwidth = picwidth/inSampleSize;
			}
		}

		Log.i("test","最终压缩比例:" +inSampleSize + "倍");
		Log.i("test", "新尺寸:" +  targetwidth + "*" +targetheight);
		return inSampleSize;
	}


	/**
	 * 以最省内存的方式读取本地资源的图片
	 *
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap readBitMap(Context context, int resId) {
		Options opt = new Options();
		opt.inPreferredConfig = Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

}
